<?php

/**
 * This is controller use for fanpage tab area
 * @author: hungnq@younetco.com
 * @property Core_Model_DbTable_Stores $_stores 
 * @property Core_Model_Store $_store 
 * @version: 0.1
 */
class Tab_IndexController extends YouNet_Controller_Action
{

	/** @var $_stores Core_Model_DbTable_Stores */
	private $_stores = null;
	
	/** @var $_store Core_Model_Store */
	private $_store = null;
	
	private $_id_page = null;	
	 
	public function init()
	{
		parent::init();		
        /*
         * Only use for authorize and redirect to url
         */
        if(!empty($this->_params['redirect_url']))
        {
            YouNet_Util::redirect($this->_params['redirect_url']);
        }
        
		$this->_id_page			= $this->_getParam('id_page', $this->_social->getIdPage());
        if(!isset($this->_params['id_page']))
        {
            YouNet_Util::redirect($this->view->pageUrl(array_merge($this->_params, array('id_page' => $this->_id_page))));
        }
        
		$this->_stores			= Core_Model_DbTable_Stores::getInstance();
		$this->_store			= $this->_stores->findStoreByPage($this->_id_page);
        
		$this->view->store = $this->_store;
		$this->_initLanguage();
        $this->view->id_page = $this->_id_page;
	}
	
	private function _initLanguage()
	{
		$language	= $this->_store->getLanguage();		
		Zend_Registry::set('language',$language);
		$file		= APPLICATION_PATH.'/modules/Tab/languages/'.$language.'/common.csv';
		if( file_exists($file) )
		{
			$translate	= Zend_Registry::get('Zend_Translate'); 
			$translate->addTranslation(
				array(
					'adapter'		=> 'csv', 
					'content'		=> $file,
					'locale'		=> 'en',
					'delimiter'		=> ';'
				)
			);
		}
	}
	
	public function preDispatch()
	{
		parent::preDispatch();
		$this->_helper->layout->setLayout('tab_' . strtolower($this->_social->getName()));		
		$this->view->menus		= $this->_store->getCategoryHierarchy();
		$this->view->store		= $this->_store;
		$this->view->arrParams	= $this->getAppParams();		
	}
			

	private function getAppParams()
	{
		$params = $this->_params;
		unset($params['module']);
		unset($params['controller']);
		unset($params['action']);
		
		$params['id_user']			= NULL;
		$params['id_social']		= NULL;
		$params['signed_request']	= NULL;
		
		if( isset($params['keyword']) && empty($params['keyword']) )
		{
			$params['keyword'] = NULL;
		}		
		if( isset($params['sort']) && empty($params['sort']) )
		{
			$params['sort'] = NULL;
		}
		return $params;
	}
	
	protected function _getRedirectUrlForAuthorization()
	{
		
	}

	public function indexAction()
	{
		$target = $this->_getParam('target');
		
		if (!$this->_getParam('skip'))
		{
			switch ($target)
			{
				case 'index':
					$this->_indexAction();
					break;
				case 'detail':
					$this->_detailAction();
					break;
				case 'more':
					$this->_moreAction();
					break;
				case 'buys':
					$this->_buysAction();
					break;
				case 'cart':
					$this->_cartAction();
					break;
                case 'ordershistory':
					$this->_ordershistoryAction();
					break;
                case 'orderdetail':
					$this->_orderdetailAction();
					break;
                default:
					$this->_indexAction();
					break;
			}
		}
        
        $this->_initLayout();
	}

	private function _getForm($sort = null)
	{
		static $form = null;
		if(!($form instanceof Tab_Form_Search))
		{
			$form = new Tab_Form_Search(array('store'=> $this->_store));
		}
		
		$form->setAction($this->view->pageUrl(
			array(
				'module'		=> 'tab',
				'controller'	=> 'index',
				'action'		=> 'index',
				'target'		=> 'index',
				'sort'			=> $sort
			),
			true)
		);
	
		if( isset($this->_params['keyword']) && trim($this->_params['keyword']) == '' )
		{
			$this->_params['keyword'] = $this->translate('keyword');
		}
		
		$form->populate($this->_params);
		return $form;
	}
	
	private function _indexAction()
	{
		$params				= $this->getAppParams() + array('id_page' => $this->_id_page);
		$pageNumber			= $this->_getParam('page', 0);
        $sort = $this->_initSort($params);
		
		$params['sort'] = $sort;
		
		$item_per_page = $this->_findItemPerPage();
		
		$paginator			= $this->_store->findProductsBelongToStore(
			array_merge(
				$params,
				array('status' => Core_Model_DbTable_Products::STATUS_SHOWN)
			),
			$pageNumber,
			$sort,
			$item_per_page
		);
		
		if (isset($params['id_category']) && $params['id_category'] != '0')
		{
			$breadscrumb = $this->_store->getCustomBreadscrumb($params['id_category']);
			$this->view->breadscrumb = $breadscrumb;
		}
		
        if ($pageNumber >= 2)
		{
			$this->view->startPage = $pageNumber+1;
		}
		else
		{
			$this->view->startPage = 2;
		}
		
		$form                       = $this->_getForm($sort);
        $this->view->form           = $form;
        $this->view->url			= $this->view->pageUrl($form->getValues());
		$this->view->paginator		= $paginator;
		$this->view->pageValues		= $params;
		$this->view->extraValues	= array();
	}
	
	private function _findItemPerPage()
	{
		$layout = (!empty($this->view->layout)) ? $this->view->layout : $this->_getParam('layout');
		switch($layout)
		{
			case Core_Model_DbTable_Stores::LAYOUT_10xLIST:
				return 10;
				break;
			case Core_Model_DbTable_Stores::LAYOUT_3x12:
				return 12;
				break;
			case Core_Model_DbTable_Stores::LAYOUT_4x16:
			case Core_Model_DbTable_Stores::LAYOUT_3xAll:
				return 16;
				break;
			default:
				return 12;
				break;
		}
	}
    
    private function _limitRecentlyViewedProducts(&$rv_products){
        if( count($rv_products) > MAX_RECENTLY_VIEWED_PRODUCTS ){
            $oldest_id = 0;
            $oldest_time = time();
            foreach ($rv_products as $id_product => $time){
                if($oldest_time > $time){
                    $oldest_id = $id_product;
                    $oldest_time = $time;
                }
            }
            if(!empty($rv_products[$oldest_id])){
                unset($rv_products[$oldest_id]);
            }
        }
    }

    private function _saveRecentViewed($id_product){
        $key	= $this->_store->getCookieRecentViewed();
        $path   = $this->view->pageUrl(array('id_page' => $this->_id_page), true);
		$rv_products    = isset($_COOKIE[$key]) ? $_COOKIE[$key] : null;
		
		if (isset($rv_products)){
            $rv_products = json_decode($rv_products, true);
            $rv_products[$id_product] = time();
		} else {
            $rv_products = array();
            $rv_products[$id_product] = time();
        }
        $this->_limitRecentlyViewedProducts($rv_products);
        $rv_products = json_encode($rv_products);
        setcookie($key, $rv_products, 0, $path);
    }
    
    private function _getRecentViewed(){
        $key	= $this->_store->getCookieRecentViewed();
        $path   = $this->view->pageUrl(array('id_page' => $this->_id_page), true);
		$rv_products    = isset($_COOKIE[$key]) ? $_COOKIE[$key] : null;
        
        if (isset($rv_products)){
            $rv_products = json_decode($rv_products, true);
            $list_products = $this->_store->getAllRecentViewedProducts($rv_products);
            return $list_products;
		} else {
            return null;
        }
    }

    private function _initLayout()
	{
		$key	= $this->_store->getCookieLayoutKey();
		$layout = isset($_COOKIE[$key]) ? $_COOKIE[$key] : null;
		
		$param_layout = $this->_getParam('layout', 0);
		
		if (empty($layout) || ($layout != $param_layout && $param_layout != 0))
		{
			$layout = $this->_getParam('layout', 0);
			if ($layout != 0)
			{
				setcookie($key, $layout, time() + 3600, $this->view->baseUrl($this->_getParam('module')));
			}
		}
		
		if (empty($layout))
		{
			$layout = $this->_store->getDefaultLayout();
		}
		
		$this->view->layout = $layout;
		
		$options = Core_Model_DbTable_Stores::getArrayLayouts($this->_store->layout);
		$layout_options = array();

		foreach ($options as $key)
		{
			$layout_options[$key]['value'] = $key;
			$layout_options[$key]['name'] = $this->translate(Core_Model_DbTable_Stores::getLayoutName($key));
			$layout_options[$key]['selected'] = false;

			if ($this->view->layout == $key)
			{
				$layout_options[$key]['selected'] = true;
			}
		}
		$this->view->layout_options = $layout_options;
        
		//to avoid the risk of css conflict in detail page
        if( !isset($this->_params['target']) || $this->_params['target'] != 'detail')
		{
			if ($this->view->layout == Core_Model_DbTable_Stores::LAYOUT_10xLIST)
			{
				$this->view->headLink()->appendStylesheet(STATIC_URL . '/css/list.css?v=' . SKIN_VERSION);
			}
			else if ($this->view->layout == Core_Model_DbTable_Stores::LAYOUT_3xAll)
			{
				$this->view->headLink()->appendStylesheet(STATIC_URL . '/css/masonry.css?v=' . SKIN_VERSION);
			}
		}
	}
	
	private function _initSort($params)
	{
		$key	= $this->_store->getCookieSortKey();
		$sort	= isset($_COOKIE[$key]) ? $_COOKIE[$key] : null;
		
		$param_sort = isset($params['sort']) ? $params['sort'] : null;
		if (empty($sort) || ($param_sort != $sort) && $param_sort != null)
		{
			$sort = !empty($params['sort']) ? $params['sort'] : null;

			if ($sort != null)
			{
				setcookie($key, $sort, time() + 3600, $this->view->baseUrl($this->_getParam('module')));
			}
		}
		return $sort;
	}
	
	public function _moreAction()
	{
		$params		= $this->getAppParams() + array('id_page' => $this->_id_page);
		$pageNumber	= $this->_getParam('page', 0);
		
		$sort = $this->_initSort($params);
		$item_per_page = $this->_findItemPerPage();
		
		$paginator			= $this->_store->findProductsBelongToStore(
			array_merge(
				$params,
				array('status' => Core_Model_DbTable_Products::STATUS_SHOWN)
			),
			$pageNumber,
			$sort,
			$item_per_page
		);
		
		$this->view->paginator		= $paginator;
		$this->view->pageValues		= $params;
		$this->view->extraValues	= array();
		$this->_helper->layout->disableLayout();
		$this->render('more');
	}
	
	private function _detailAction()
	{
		$params				= $this->getAppParams() + array('id_page' => $this->_id_page);
		$pageNumber			= $this->_getParam('page', 1);
		$sort = $this->_initSort($params);
		$params['sort'] = $sort;
		$item_per_page = $this->_findItemPerPage();
		
		$id_product = $this->_getParam('id_product', 0);
		if ($id_product > 0)
		{
			$product = $this->_store->findProductById($id_product);
            // Check status product
			if (!empty($product))
			{
				if ($product->status != Core_Model_DbTable_Products::STATUS_SHOWN)
				{
					$this->view->warning = $product->name;
					$this->_params['target'] = NULL;
					$this->_params['id_product'] = NULL;
					$this->_params['id_category'] = NULL;
					$this->_indexAction();
					return;
				}
				if( !isset($params['id_category']) )
				{
					$params['id_category'] = $product->getCustomCategory()->path . '%';
				}
				$paginator			= $this->_store->findProductsBelongToStore(array_merge(
						$params,
						array('status' => Core_Model_DbTable_Products::STATUS_SHOWN)
					), $pageNumber, $sort, $item_per_page);
				$relatedProduct 	= $this->randomProductFromPaginator($paginator,$product->id);
				
				$this->view->relatedProducts = $relatedProduct;
				$this->view->product = $product;
				$this->view->form = $this->_getForm();
				$this->view->url = $this->view->pageUrl(array_merge($this->_getForm()->getValues(), array('target' => NULL, 'id_product' => NULL)));
				$id_category = $this->_getParam('id_category', '');
				$this->view->path = (!empty($id_category)) ? $id_category : $product->getCustomCategory()->path;
				$this->view->pageValues = $params;
                
                if(!empty($this->_user['id'])){
                    $this->view->is_authorized = true;
                } else {
                    $this->view->is_authorized = false;
                }
                
                $this->_saveRecentViewed($product->id);
                
				$this->render('detail');
			}
			else
			{
                $this->view->warning = true;
                $this->_params['target'] = NULL;
                $this->_params['id_product'] = NULL;
                $this->_params['id_category'] = NULL;
				$this->_indexAction();
                return;
			}
		}
	}
	public function randomProductFromPaginator($paginator,$id_product)
	{
		$products = array();
		foreach ($paginator as $product)
		{
			if ($product->id != $id_product)
				$products[] = $product;
		}
		shuffle($products);
		return $products;
	}
	public function _buysAction()
	{
		$this->disableAutoRender();
		$id_product = $this->_getParam('id_product', 0);
		if($id_product>0)
		{
			$buys = new Core_Model_DbTable_Product_Buys();
			$buys->insertProductBuys(
					$id_product, 
					$this->_store->id, 
					$this->_social->getIdPage(),
					$this->_id_user
			);
		}
		echo $id_product;
	}
    
    public function _cartAction()
    {
        if(empty($this->_store->shopping_cart_setting)){
            YouNet_Util::parentRedirect($this->_social->pageUrl(array(), $this->_id_page));
        }
        $params				= $this->getAppParams() + array('id_page' => $this->_id_page);
        $sort = $this->_initSort($params);
        $form_search = $this->_getForm($sort);
        $this->view->form_search = $form_search;
        
        $cookie_key	= "cart_products_" . $this->_store->id;
        $cookie_path=  $this->view->pageUrl(array('id_page' => $this->_id_page), true);
		$cart_products = isset($_COOKIE[$cookie_key]) ? $_COOKIE[$cookie_key] : null;
        $cart_products = json_decode($cart_products, true);
        $total_price   = 0;
        $total_items   = 0;
        $list_products = array();
        if(!empty($cart_products)){
            foreach ($cart_products as $key => $product)
            {
                if($product['quantity'] > 0){
                    $product_info = $this->_store->findProductById($key);
                    if(!empty($product_info)){
                        if ($product_info->status == Core_Model_DbTable_Products::STATUS_SHOWN){
                            $list_products[$key] = $product_info->toArray();

                            $list_products[$key]['quantity'] = $product['quantity'];
                            $list_products[$key]['thumbnail'] = $product_info->getPrimaryThumbImageUrl();
                            $total_price += $list_products[$key]['quantity'] * $list_products[$key]['price'];
                            $total_items += $product['quantity'];
                        } else {
                            unset($cart_products[$key]);
                        }
                    } else {
                        unset($cart_products[$key]);
                    }
                } else {
                    unset($cart_products[$key]);
                }
            }
            
            if(!empty($cart_products)){
                $cart_products = json_encode($cart_products);
                setcookie($cookie_key, $cart_products, 0, $cookie_path);
            } else {
                setcookie($cookie_key, "", time(), $cookie_path);
            }
        }
        
        $form_order = new Tab_Form_Order();
        $form_order_data = $this->getRequest()->getPost();
        if(!empty($form_order_data['form_submitted']))
        {
            if(!empty($list_products) && $total_items > 0){
                if($form_order->isValid($form_order_data)){
                    if(!empty($this->_store) && !empty($this->_id_page))
                    {
                        if(!empty($this->_user['id']))
                        {
                            $this->_params['id_user'] = $this->_user['id'];
                        }
                        $this->_params['id_page'] = $this->_id_page;
                        $this->_params['total_price'] = $total_price;
                        $id_cart = Core_Model_DbTable_Carts::getInstance()->addCart($this->_params, $this->_store->id, $list_products);
                        if(!empty($id_cart))
                        {
                            $cart_url = $this->_social->url('/store/cart/detail/id_page/' . $this->_id_page 
                                    . '/id_store/' .$this->_store->id . '/id/' . $id_cart);
                            
                            $form_order->populate(array(
                                'user_note'   => ''
                            ));
                            $cookie_path = $this->view->pageUrl(array('id_page' => $this->_id_page), true);
                            setcookie($cookie_key, "", time(), $cookie_path);
                            $list_products = array();
                            
                            $this->_helper->flashMessenger->setNamespace('msg_add_cart')
                                ->addMessage(sprintf(YouNet_Util::translate('MSG_ADD_CART_SUCCESSFUL'), $id_cart));
                            
                            YouNet_Util::redirect($this->view->pageUrl(array('target' => 'orderdetail', 'id_cart' => $id_cart)));
                        }
                    }
                }
            }
            else
            {
                $form_order->populate($form_order_data);
                $this->view->msg_shopping_cart = array('MSG_CART_EMPTY');
            }
        }
        else {
            if(!empty($this->_user['id']))
            {
                $latest_order = Core_Model_DbTable_Carts::getInstance()->getLatestCart($this->_user['id']);
                if(empty($latest_order))
                {
                    $form_order->populate(array(
                        'user_name'     => $this->_user->name,
                        'user_email'    => $this->_user->email
                    ));
                }
                else
                {
                    $form_order->populate(array(
                        'user_name'     => $latest_order->user_name,
                        'user_email'    => $latest_order->user_email,
                        'user_phone'    => $latest_order->user_phone,
                        'user_location' => $latest_order->user_location
                    ));
                }
            }
        }
        $this->view->list_products = $list_products;
        $this->view->form_order = $form_order;
        
        $this->view->pageValues = $params;
        $this->view->format_currency = json_encode(Core_Util::getFormatCurrency($this->_store->unit_code));
        $this->view->rv_products = $this->_getRecentViewed();
        
        if(!empty($_COOKIE["is_add_to_cart_" . $this->_store->id])){
            $this->view->msg_shopping_cart = array(
                sprintf(YouNet_Util::translate('MSG_ADD_TO_CART_SUCCESSFUL'))
            );
            setcookie("is_add_to_cart_" . $this->_store->id, "", time(), $cookie_path);
        }
        
        $this->render('cart');
    }
    
    protected function _notifyOrder($order_info, $order_details)
    {
        $notify_email = preg_replace('/\s+/', "", $this->_store->notify_email);
        if(!empty($notify_email))
        {    
			$from       	= 'support@younetmedia.com';
        	$from_label 	= 'YouNet Media';
            $campaign_url   = $this->_social->url('/store/cart/detail/id_page/' . $this->_id_page . '/id_store/' .$this->_store->id . '/id/' . $order_info->id);
            
            $to         = explode( ",", $notify_email);
            $subject    = '[YouNet Media] "' . $this->_store->page_name . '| ' . $this->_store->name . '": new order by ' . $order_info->user_name;
            $template   = 'templateNotifyOrder.phtml';
            $data       = array(
                'page_name'     => $this->_store->page_name,
                'object_name'   => $this->_store->name,
                'user_name'     => $order_info->user_name,
                'date_time'     => $order_info->time_sent,
                'campaign_url'  => $campaign_url,
                'order_info'    => $order_info,
                'order_details' => $order_details,
                'store'         => $this->_store,
                'social'        => $this->_social,
                'view'          => $this->view
            );
            
            $this->_sendEmail($from, $from_label, $to, $subject, $template, $data);
        }
    }
    
    protected function _sendEmail($from, $from_label, $to, $subject, $template, $data)
    {
        try{
            $mail			= new Zend_Mail('UTF-8');
            $mail->setFrom($from, $from_label);
            $mail->setBodyHtml($this->view->partial($template, $data));
            $mail->addTo($to);
            $mail->setSubject($subject);
            $mail->send();
        } catch (Exception $e){var_dump($e);}
    }
    
    public function _ordershistoryAction(){
        if(empty($this->_store->shopping_cart_setting)){
            YouNet_Util::parentRedirect($this->_social->pageUrl(array(), $this->_id_page));
        }
        $params				= $this->getAppParams() + array('id_page' => $this->_id_page);
        $sort = $this->_initSort($params);
        $form_search = $this->_getForm($sort);
        $this->view->form_search = $form_search;
        $this->_params['id_page'] = $this->_id_page;
        $this->_params['id_store'] = $this->_store->id;
        
        $page = $this->_getParam('page', 1);
        $paginator = Zend_Paginator::factory(Core_Model_DbTable_Carts::getInstance()->getOrderHistory($this->_params));
        $paginator->setCurrentPageNumber($page);
        $paginator->setItemCountPerPage(ITEM_COUNT_PER_PAGE);
        $this->view->paginator = $paginator;
        
        $this->view->rv_products = $this->_getRecentViewed();
        $this->view->msg_history = $this->_helper->flashMessenger->setNamespace('msg_history')->getMessages();
        $this->render('ordershistory');
    }
    
    public function _orderdetailAction(){
        if(empty($this->_store->shopping_cart_setting)){
            YouNet_Util::parentRedirect($this->_social->pageUrl(array(), $this->_id_page));
        }
        $params				= $this->getAppParams() + array('id_page' => $this->_id_page);
        $sort = $this->_initSort($params);
        $form_search = $this->_getForm($sort);
        $this->view->form_search = $form_search;
        
        $this->_params['id_page'] = $this->_id_page;
        $this->_params['id_store'] = $this->_store->id;
        
        $cart = Core_Model_DbTable_Carts::getInstance()->getHistoryCart($this->_params);
        if(!empty($cart)){
            $this->view->list_products = $cart->getOrderHistoryDetail();
        } else {
            $this->_helper->flashMessenger->setNamespace('msg_history')
                                ->addMessage(sprintf(YouNet_Util::translate('MSG_VIEW_ORDER_DELETED')));
                        
            YouNet_Util::redirect($this->view->pageUrl(array('target' => 'ordershistory', 'id_cart' => null)));
        }
        
        $this->view->msg_add_cart = $this->_helper->flashMessenger->setNamespace('msg_add_cart')->getMessages();
        if(!empty($this->view->msg_add_cart)){
            $this->_notifyOrder($cart, $this->view->list_products);
        }
        
        $this->view->cart = $cart;
        $this->view->rv_products = $this->_getRecentViewed();
        $this->render('orderdetail');
    }
}
